import { h, Component } from 'preact';
import { connect } from 'preact-redux';
import DockBar from '~/components/DockBar';
import HeaderBar from '~/components/HeaderBar';
import ScrollLoading from '~/components/ScrollLoading';
import moment from 'moment';
import { creatResume, modifyResume, deleteResume, getMyResume } from '~/api';
import Loading from '~/components/Loading';
import { Link } from 'preact-router/match';
import Select from '~/components/Select';
import Modal from '~/components/Modal';
import classNames from 'classnames';
import validate, { VRequire } from '~/utils/validate';
import s from './Resume.scss';

class Resume extends Component {

	constructor(props){
		super(props);
		this.state = {
			list: [],
			edit: false,
			editStartDate: null,
			editEndDate:  null,
			editCompany:  null,
			editJobTitle:  'null',
			editContent:  null,
			editId:  null,
			showError: false,
			message: null,
			showModal: false,
			deletresume: false,
			cookId: null
		};
	}

	componentWillMount() {
		if (this.props.user.id) {
			this.setState({
				cookId: this.props.user.id
			});
			this.getMyResume(this.props.user.id);
		}
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.user !== this.props.user) {
			this.setState({
				cookId: nextProps.user.id
			});
			this.getMyResume(nextProps.user.id);
		}
	}

	getMyResume = (id) => {
		getMyResume(id).then(res => {
			const data = res;
			this.setState({
				list: data
			});
		}).catch(error => {
			Loading.hide();
			this.showError(error.message || '网络异常！请重试');
		});
	}

	handleCloseModal = () => {
		this.setState({ showModal: false });
	}

	handleShowEdit = (id) => () => {
		if (id) {
			for (let i = 0; i < this.state.list.length; i += 1) {
				if (id === this.state.list[i].id) {
					this.setState({
						editStartDate: this.state.list[i].startDate,
						editEndDate: this.state.list[i].endDate,
						editCompany: this.state.list[i].company,
						editJobTitle: this.state.list[i].jobTitle,
						editContent: this.state.list[i].content,
						editId: this.state.list[i].id,
						deletresume: true,
						showModal: true,
						endDateHolder: '不填写默认为至今'
					});
				}
			}
		} else {
			this.setState({
				editStartDate: null,
				editEndDate:  null,
				editCompany:  null,
				editJobTitle:  'null',
				editContent:  null,
				editId:  null,
				deletresume: false,
				showModal: true
			});
		}
	}

	showError = (message) => {
		this.setState({
			message,
			showError: true
		});
	}

	handleValidate = () => {
		const {editStartDate,
				editEndDate,
				editCompany,
				editJobTitle} = this.state;
		return validate(
			VRequire(editStartDate) ? '请填写开始时间' : null,
			// VRequire(editEndDate) ? '请填写结束时间' : null,
			VRequire(editCompany) ? '请填写公司名称' : null,
			VRequire(editJobTitle) ? '请选择职位' : null
		);
	}

	handleModify = () => {
		console.log(this.state.cookId, 'cookId');
		const {editStartDate,
				editEndDate,
				editCompany,
				editJobTitle,
				editContent,
				cookId,
				editId} = this.state;

		if (this.handleValidate()) {
			this.showError(this.handleValidate());
			return;
		}

		Loading.show();

		modifyResume({

			company : editCompany,
			jobTitle : editJobTitle,
			startDate : editStartDate,
			endDate : editEndDate,
			content: editContent,
			cookId,
			id: editId,
			"updateTime" : "2017-05-15T20:56:38+08:00",
			"createTime" : "2017-05-15T20:56:41+08:00"
		}).then((res) => {
			Loading.hide();
			console.log(res);
			this.getMyResume(this.props.user.id);
			this.setState({
				showModal: false
			});
		}).catch(error => {
			Loading.hide();
			this.showError(error.message || '网络异常！请重试');
		});
	}

	handleDelete = () => {
		const {editId} = this.state;
		Loading.show();
		deleteResume(editId).then((res) => {
			Loading.hide();
			console.log(res);
			this.getMyResume(this.props.user.id);
			this.setState({
				showModal: false
			});
		}).catch(error => {
			Loading.hide();
			this.showError(error.message || '网络异常！请重试');
		});
	}

	handleSubmit = () => {
		const {editStartDate,
				editEndDate,
				editCompany,
				editJobTitle,
				editContent,
				cookId} = this.state;

		if (this.handleValidate()) {
			this.showError(this.handleValidate());
			return;
		}

		Loading.show();

		creatResume({
			company : editCompany,
			jobTitle : editJobTitle,
			startDate : editStartDate,
			endDate : editEndDate,
			content : editContent,
			cookId
		}).then((res) => {
			Loading.hide();
			console.log(res);
			this.getMyResume(this.props.user.id);
			this.setState({
				showModal: false
			});
		}).catch(error => {
			Loading.hide();
			this.showError(error.message || '网络异常！请重试');
		});
	}

	handlePlaceholder = (e) => {
		// this.removeAttribute('placeholder');
		this.setState({editEndDate: e.target.value});
		if (this.state.editEndDate) {
			e.target.placeholder = '';
		}
	}

	render() {
		console.log('s', s);
		const { list, endDateHolder } = this.state;
		return (
			<div className={s.root}>
				<HeaderBar
					setTitle="编辑简历"
					goBack
				>
					<span className={classNames('icon-add', 'white', s.edite)} onClick={this.handleShowEdit()}/>
				</HeaderBar>
				<div className={s.listwarp}>
					<div>
						<ul className={`${s.list} nls`} >
							{
								list.map(item => (
									<li className="clearfix" key={item.id} onClick={this.handleShowEdit(item.id)}>
										<h3 className="txt_cut font orangered">{moment(item.startDate).format('YYYY-MM-DD')} 到 {item.endDate ? moment(item.endDate).format('YYYY-MM-DD') : '至今'}</h3>
										<div className="clearfix">
											<div className="w4-8 fl txt_cut">
												{item.company ? item.company : '休息中'}
											</div>
											<div className="w4-8 fr txt_cut">
												岗位：{item.jobTitle}
											</div>
										</div>
										<p className="txt_cut gray font-small">{item.content}</p>
									</li>
								))
							}
						</ul>
					</div>
				</div>
				<Modal
					contentLabel="ModalB"
					isOpen={this.state.showModal}
					onRequestClose={this.handleCloseModal}
					shouldCloseOnOverlayClick={true}
				>
					<ul className={classNames('nls pd1 clearfix pdt3 w9 center', s.form)}>
						<li className="mgb1 w3 al-r">开始时间:&nbsp;</li>
						<li className="mgb1 w7">
							<input className="ww" type="date"
							value={moment(this.state.editStartDate).format('YYYY-MM-DD')}
							onChange={ e => this.setState({editStartDate: e.target.value}) }
							placeholder="开始时间" />
						</li>
						<li className="mgb1 w3 al-r">结束时间:&nbsp;</li>
						<li className="mgb1 w7">
							<input className={`${s.date} ww`} type="date"
							onChange={ this.handlePlaceholder }
							value={moment(this.state.editEndDate).format('YYYY-MM-DD')} placeholder="不填写默认为至今" />
						</li>
						<li className="mgb1 ww">
							<input type="text"
							onChange={ e => this.setState({editCompany: e.target.value}) }
							value={this.state.editCompany} placeholder="公司" />
						</li>
						<li className="mgb1 ww">
							<Select name="" id="" value={this.state.editJobTitle}
								onChange={(e) => {this.setState({editJobTitle: e.target.value});}}
							>
								<option value={null}>请选择</option>
								<option value="0">水台</option>
								<option value="1">配菜</option>
								<option value="2">打荷</option>
								<option value="3">砧板</option>
								<option value="4">上杂</option>
								<option value="5">油鸡</option>
								<option value="6">尾锅</option>
								<option value="7">五锅</option>
								<option value="8">四锅</option>
								<option value="9">三锅</option>
								<option value="10">二锅</option>
								<option value="11">头锅</option>
								<option value="12">总厨</option>
								<option value="13">顾问</option>
								<option value="14">其他</option>
							</Select>
						</li>
						<li className="mgb1 ww">
							<textarea className={s.textarea} placeholder="职能描述" cols="30" rows="5"
							onChange={ e => this.setState({editContent: e.target.value}) }
							value={this.state.editContent} />
						</li>
						<li className="clearfix ww">
							{
								this.state.deletresume ?
								<div>
									<div className="fl w4-8 btn" onClick={this.handleModify}>修改</div>
									<div className="fr w4-8 btnb" onClick={this.handleDelete}>删除</div>
								</div>
								:
								<div>
									<div className="fl w4-8 btn" onClick={this.handleSubmit}>创建</div>
									<div className="fr w4-8 btnb" onClick={this.handleCloseModal}>取消</div>
								</div>
							}
						</li>
					</ul>
				</Modal>
				<Modal
					contentLabel="Modal"
					isOpen={this.state.showError}
					onRequestClose={() => {this.setState({showError: false});}}
					shouldCloseOnOverlayClick={true}
				>
					<h3 className="al-c pdt3">{this.state.message}</h3>
				</Modal>
			</div>
		);
	}
}

function mapStateToProps(state) {
	return {
		user: state.user
	};
}

export default connect(mapStateToProps)(Resume);

